package com.qinglei.recoup.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qinglei.recoup.system.domain.NurseOnline;
import com.qinglei.recoup.system.dao.NurseOnlineMapper;
import com.qinglei.recoup.system.service.NurseOnlineService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author syp
 */
@Service
@Slf4j
public class NurseOnlineServiceImpl extends ServiceImpl<NurseOnlineMapper, NurseOnline> implements NurseOnlineService {


    @Resource
    private NurseOnlineService nurseOnlineService;

    /**
     * 状态 - 离线
     */
    public static final int STATUS_OFFLINE = 0;
    /**
     * 保存登录记录
     * @param userId
     * @return
     */
    @Override
    public boolean saveLogin(Long userId) {
        NurseOnline nurseOnline = new NurseOnline();
        nurseOnline.setUserId(userId);
        nurseOnline.setStatisticsDate(LocalDate.now());
        nurseOnline.setLoginTime(LocalDateTime.now());
        return this.save(nurseOnline);
    }

    /**
     * 保存登出记录
     * @param userId
     * @return
     */

    @Override
    public boolean saveLogout(Long userId) {
        NurseOnline one = this.getOne(Wrappers.<NurseOnline>lambdaQuery().eq(NurseOnline::getUserId, userId)
                .orderByDesc(NurseOnline::getLoginTime).last("limit 1"));
        if (one == null) {
            log.warn("无登录记录 userId: {}", userId);
            return false;
        }
        //获取登录时的秒数
        long loginTime = one.getLoginTime().toEpochSecond(ZoneOffset.of("+8"));
        //登出时间
        LocalDateTime logoutTime = LocalDateTime.now();
        //在线时长
        long onlineTime = logoutTime.toEpochSecond(ZoneOffset.of("+8")) - loginTime;
        NurseOnline updateOne = new NurseOnline();
        updateOne.setId(one.getId());
        updateOne.setLogoutTime(logoutTime);
        updateOne.setOnlineTime((int)onlineTime);
        updateOne.setStatus(STATUS_OFFLINE);
        return this.updateById(updateOne);
    }

    /**
     * 获取指定天的在线时长（秒）
     * @param userId
     * @param day
     * @return
     */
    @Override
    public Integer getOnlineTimeByDay(Long userId, LocalDate day) {
        int ret = 0;
        List<NurseOnline> nurseOnlines = this.baseMapper.selectListByDay(userId, day, day);
        if(nurseOnlines.size()>0){
            System.out.println();
        }
//        LocalDateTime startTime = LocalDateTime.of(day, LocalTime.parse("00:00:00"));
        LocalDateTime endTime = LocalDateTime.of(day, LocalTime.parse("23:59:59"));
//        LocalDateTime now = LocalDateTime.now();


        for (int i = 0; i < nurseOnlines.size(); i++) {
            NurseOnline nurseOnline = nurseOnlines.get(i);
                if (nurseOnline.getLogoutTime() == null || nurseOnline.getOnlineTime()<1) {
                    if(nurseOnline.getLogoutTime() == null){
                        if (i==nurseOnlines.size()-1) {
                            //当天最后一次登录记录
                            ret += Duration.between(nurseOnline.getLoginTime(), endTime).toMillis() / 1000;
                        } else {
                             //不是当天最后一次登录,,取下一次登录开始时间计算
                            NurseOnline nurse = nurseOnlines.get(i+1);
                            ret += Duration.between(nurseOnline.getLoginTime(), nurse.getLoginTime()).toMillis() / 1000;
                        }
                    }else{
                        ret += Duration.between(nurseOnline.getLoginTime(), nurseOnline.getLogoutTime()).toMillis() / 1000;
                    }

    //                else if (nurseOnline.getLoginTime().isBefore(startTime) && nurseOnline.getLogoutTime().isAfter(endTime)) {
    //                    // 当天之前登录的，当天之后登出的
    //                    ret += Duration.between(startTime, endTime).toMillis() / 1000;
    //                } else if (nurseOnline.getLoginTime().isBefore(startTime) && nurseOnline.getLogoutTime().isBefore(now)) {
    //                    // 当天之前登录的，当天登出的
    //                    ret += Duration.between(startTime, nurseOnline.getLogoutTime()).toMillis() / 1000;
    //                } else if (nurseOnline.getLoginTime().isBefore(startTime) && nurseOnline.getLogoutTime().isAfter(endTime)) {
    //                    // 当天登录的，当天之后登出的，
    //                    ret += Duration.between(nurseOnline.getLoginTime(), endTime).toMillis() / 1000;
    //                } else {
    //                    ret += Duration.between(nurseOnline.getLoginTime(), nurseOnline.getLogoutTime()).toMillis() / 1000;
    //                }
                }else{
                    ret+=nurseOnline.getOnlineTime();
                }
        }

        return ret;
    }

    @Override
    public void updateOnline() {
        List<NurseOnline> nurseOnlines = this.baseMapper.selectList(new QueryWrapper<>());
        for (NurseOnline nurseOnline : nurseOnlines) {
            if(nurseOnline.getLoginTime()!=null && nurseOnline.getLogoutTime()!=null ){
                nurseOnline.setOnlineTime( Integer.valueOf(Duration.between(nurseOnline.getLoginTime(), nurseOnline.getLogoutTime()).toMillis() / 1000+""));
            }
            nurseOnlineService.saveOrUpdate(nurseOnline);
        }

    }
}
